package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    /**
     * 获取验证码
     * @param session
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMsg(HttpSession session, @RequestBody User user){
        //1、后台获取手机号【13399998888】
        String phone = user.getPhone();
        //2、随机生成六位数字验证码【123456】
        String s = RandomUtil.randomNumbers(6);
        //3、调用SMSUtils,给该手机号发送相应的验证码短信
        //SMSUtils.sendMessage("瑞吉外卖","",phone,s);
        log.info("验证码：{}",s);
        //4、将该验证码存入到session中，使用手机号作为key，值就是验证码 存入Redis中
        session.setAttribute(phone,s);
        System.out.println(s);
        return R.success("验证码发送成功");
    }

    /**
     * 登录
     * @param session
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R login(HttpSession session, @RequestBody Map map){
        //1、用户输入手机收到的验证码，点击登录
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            return R.error("手机号或者验证码不能为空");
        }
        //2、收到用户输入的手机号【13399998888】+验证码【666666】
        //3、和真实的验证码【在哪呢？从session中取验证码】进行比对  从Redis中获取
        String code1 = (String) session.getAttribute(phone);
        if (code.equals(code1)){
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone,phone);
            User user = userService.getOne(qw);
            if (user==null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("loginPhone",user);
            return R.success("登录成功");
        }
        return R.error("登陆失败");
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R loginout(HttpSession session){
        session.removeAttribute("loginPhone");
        return R.success("退出成功");
    }
}
